from datetime import datetime
from peewee import *
from typing import Optional

from common.enum.form_items_key import FormItemsKey
from .database_pool import DatabasePool

db = DatabasePool()


class DataDictionary(Model):
    # 字典键
    dict_key = CharField(max_length=50, unique=True)
    # 字典值
    dict_value = TextField()
    # 字典描述
    dict_desc = TextField(null=True)
    # 创建时间
    create_time = DateTimeField(default=datetime.now)
    # 更新时间
    update_time = DateTimeField(default=datetime.now)

    class Meta:
        database = db.database
        table_name = "data_dictionary"


class DataDictionaryDas:
    # 增加数据字典项
    def add_dictionary_item(
        self, dict_key: str, dict_value: str, dict_desc: Optional[str] = None
    ):
        try:
            DataDictionary.create(
                dict_key=dict_key,
                dict_value=dict_value,
                dict_desc=dict_desc,
                create_time=datetime.now(),
                update_time=datetime.now(),
            )
            AntLogger.info(f"字典项 {dict_key} 已添加成功。")
        except IntegrityError:
            AntLogger.info(f"字典键 {dict_key} 已存在，无法重复添加。")

    # 更新数据字典项
    def update_dictionary_item(
        self,
        dict_key: str,
        dict_value: Optional[str] = None,
        dict_desc: Optional[str] = None,
    ):
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            if dict_value is not None:
                item.dict_value = dict_value
            if dict_desc is not None:
                item.dict_desc = dict_desc
            item.update_time = datetime.now()
            item.save()
            AntLogger.info(f"字典项 {dict_key} 已更新成功。")
        except DoesNotExist:
            AntLogger.info(f"字典键 {dict_key} 不存在，无法更新。")

    # 查询所有数据字典项
    def get_all_items(self):
        items = DataDictionary.select()
        return list(items)

    # 根据键查询数据字典项
    def get_item_by_key(self, dict_key: str) -> Optional[DataDictionary]:
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            return item
        except DoesNotExist:
            AntLogger.info(f"未找到字典键 {dict_key} 的记录。")
            return None
        
    # 根据键查询数据字典项
    def get_item_by_form_enum(self, enum_member: FormItemsKey) -> Optional[DataDictionary]:
        """
        根据 FormItemsKey 枚举成员的 key 查询数据字典项。

        :param enum_member: FormItemsKey 枚举成员
        :return: 查询到的数据字典项，或 None
        """
        try:
            # 使用 FormItemDto 对象中的 form_key 属性进行查询
            item = DataDictionary.get(DataDictionary.dict_key == enum_member.form_item.form_key)
            return item
        except DoesNotExist:
            AntLogger.info(f"未找到字典键 {enum_member.form_item.form_key} ({enum_member.form_item.form_desc}) 的记录。")
            return None

    # 根据一组键批量查询数据字典项
    def get_items_by_keys(self, dict_keys: list[str]) -> list[DataDictionary]:
        try:
            if not dict_keys:
                AntLogger.info("查询键列表为空，返回空列表。")
                return []

            # 使用 IN 查询批量获取记录
            items = DataDictionary.select().where(
                DataDictionary.dict_key.in_(dict_keys)
            )
            return list(items)
        except Exception as e:
            AntLogger.info(f"批量查询时发生错误: {e}")
            return []

    # 删除数据字典项
    def delete_item_by_key(self, dict_key: str):
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            item.delete_instance()
            AntLogger.info(f"字典项 {dict_key} 已被删除。")
        except DoesNotExist:
            AntLogger.info(f"未找到字典键 {dict_key} 的记录，无法删除。")
